<template lang="pug">
    .index
        header
            .search-input
                svg.icon.search-icon(aria-hidden="true")
                    use(xlink:href='#icon-search')
                input(type="search",v-model="searchInput",ref="searchInput",@keyup.13="search",placeholder="请输入搜索内容",@focus="focus",@blur="blur")
                svg.icon.cancel(:class="{activeCancel:isActive}",aria-hidden="true",v-if="searchInput",@click="cancel",@touchstart.prevent="cancel")
                    use(xlink:href="#icon-close")
            message
        main
            .products(ref="products")
                .refresh(ref="refresh")
                    svg.icon(aria-hidden="true",ref="icon")
                        use(xlink:href="#icon-shuaxin")
                section(v-for="item in $store.state.products", :key="item.ej_good_id")
                    router-link.detail(:to="'./detail?id='+item.ej_good_id")
                        .topRight
                            .price(v-text="item.ej_good_rent_price+'元/'+item.ej_good_rent_time")
                            .time(v-text="item.ej_good_publish_time")
                        .title(v-text="item.ej_good_title")
                        .address(v-text="item.ej_good_contact_address")
                        - var n = 1
                        .attributes
                            while n < 6
                                .attribute(v-show="item.ej_good_attribute" + n, v-text="item.ej_good_attribute" + n++)
                        img(:src="item.ej_good_picture_url")
                        .right
                            .owner(v-text="item.ej_user_name")
                            .contact(v-text="item.ej_good_contact_phone")
                .loading(v-text="loadingTip")
        app-footer
</template>

<script type="es6">
	import searchInput from 'component/common/searchInput'
	import message from 'component/common/message'
	import {getProductList} from 'dataAPI/product'
    import appFooter from 'component/common/footer/footer'
    const util = require("util")
//	    const _ = require("underscore")
	export default {
		name: 'index',
		data () {
			return {
				pageNumber: 1,
				pageSize: 10,
				state: 'normal',
				isRefresh: false,
				loadingTip: '加载更多',
				searchInput: '',
				isActive: false,
                backTimer: null,
                rotateTimer:null
			}
		},
		mounted (){
//			this.$refs.searchInput.blur()
//			this.searchInput = this.$store.state[this.searchKeyName]
			this.getProducts(1).then((response) => {
				this.$store.commit('updateProducts', response.data.data.list)
			}).then(()=>{this.initScroll()})
		},
		components: {
			searchInput,
			message,
            appFooter
		},
		methods: {
			cancel(ev){
				this.searchInput = ''
				this.$refs.searchInput.focus()
			},
			focus(ev){
				this.isActive = true
			},
			blur(ev){
				this.isActive = false
			},
			search(){
				this.$store.commit('updateProductSearchKey', this.searchInput)
				this.getProducts(1).then((response) => {
                  this.pageNumber = 1
                  this.$store.commit('updateProducts', response.data.data.list)
				})
			},
			getProducts(){
				return getProductList(this.pageSize, this.pageNumber, this.$store.state.productSearchKey).then((response)=>{
                  if (response.data.data.pageNumber === response.data.data.totalPage){
                    this.loadingTip = '没有更多'
                  }else if(response.data.data.pageNumber < response.data.data.totalPage){
                    this.loadingTip = '加载更多'
                  }
                  return Promise.resolve(response)
                })
			},
			nextPage(){
				if (this.loadingTip === '没有更多' || this.loadingTip === '加载中...') {
					return
				}
				this.loadingTip = '加载中...'
                const pageNumber = this.pageNumber + 1
				this.getProducts(pageNumber).then(response => {
					setTimeout(() => {
                        this.pageNumber = this.pageNumber + 1
						console.log("next page products=", response)
						this.$store.commit('updateNextPageProducts', response.data.data.list)
					}, 3000)
				})
			},
			refresh(){
			    clearInterval(this.rotateTimer);
				const rotatePercent = 20
				this.isRefresh = true
				const refresh = this.$refs.icon
				const transformStr = refresh.style.transform
				let current = transformStr.substring(transformStr.indexOf('(') + 1, transformStr.indexOf(')') - 3);
				console.log('current', current)
				this.rotateTimer = setInterval(() => {
					refresh.style.setProperty('transform', 'rotate(' + rotatePercent * ++current + 'deg)');
				}, 30)
				return this.getProducts(1).then(response => {
					setTimeout(() => {
                        this.pageNumber = 1
						clearInterval(this.rotateTimer)
						this.isRefresh = false;
						this.moveTo(0)
						this.$store.commit('updateProducts', response.data.data.list)
					}, 3000)

				})
			},
			inputBlur(){
				let input = document.getElementsByTagName("input")
				for (let i = 0, iLength = input.length; i < iLength; i++) {
					input[i].blur()
				}
			},
			setProElementTop(top, min, max){
				let dragPercent = 0.7
				let proElement = this.$refs.products
				if (top < min) {
					proElement.style.top = this.fixPx(min - Math.pow(min - top, dragPercent))
					console.log('next page')
					this.nextPage()
				} else if (top > max) {
					proElement.style.top = this.fixPx(max + Math.pow(top - max, dragPercent))
				} else {
					proElement.style.top = this.fixPx(top)
				}
			},
			moveTo(targetTop){
				const intervalTime = 30
				const proElement = this.$refs.products
				const easyIn = 2
                clearInterval(this.backTimer)
				this.backTimer = setInterval(() => {
					const currentTop = proElement.offsetTop
					const diff = targetTop - currentTop
					if (diff === 0) {
						clearInterval(this.backTimer)
						return
					}
					let speed = diff >= 0 ? Math.ceil(diff / easyIn) : Math.floor(diff / easyIn)
					proElement.style.top = currentTop + speed + 'px';
				}, intervalTime)
			},
			fixPx(number){
				return (number >= 0 ? Math.floor(number) : Math.ceil(number)) + 'px'
			},
			getClientY(e){
				return e.touches[0].clientY;
			},
			preRefreshAction(beyond){
				const rotatePercent = 25
				this.$refs.icon.style.setProperty('transform', 'rotate(' + rotatePercent * beyond + 'deg)');
			},
			initScroll(){
				const intervalTime = 30; // 30ms do interval
				const maxTop = 0;
				const proElement = this.$refs.products
				const scrollHeight = document.documentElement.clientHeight - document.querySelector("header").offsetHeight - document.querySelector("footer").offsetHeight
				const refreshTop = Math.abs(this.$refs.refresh.offsetHeight + 2 * this.$refs.refresh.offsetTop)
//				console.log(refreshTop)
//				console.dir(this.$refs.refresh)
				let inertiaTimer = null // make inertia
				proElement.addEventListener('touchstart', e => {
//					console.log('touch start', e)
					this.inputBlur();
					if (e.touches.length > 1) {
//						console.log('touches > 1')
						return
					}
					const originY = this.getClientY(e)
					const originHeight = proElement.offsetHeight;
					const originTop = proElement.offsetTop
					const touchStartTime = new Date().getTime()
					const minTop = scrollHeight - originHeight;
					clearInterval(inertiaTimer)
					let touchMove = e => {
						const clientY = this.getClientY(e)
						const originDistance = clientY - originY
						const currentTop = originTop + originDistance
//						console.log('originDistance', originDistance)
						this.setProElementTop(currentTop, minTop, maxTop)
						if (proElement.offsetTop > maxTop && !this.isRefresh) {
							this.preRefreshAction(proElement.offsetTop - maxTop)
						}
					}
					document.addEventListener('touchmove', touchMove, {passive: true})
					let touchEnd = e => {
						let nowTop = proElement.offsetTop;
						const realDistance = nowTop - originTop;
						const touchEndTime = new Date().getTime();
						const timeCycle = (touchEndTime - touchStartTime) / intervalTime;
						let speed = realDistance / timeCycle;
						const direction = -speed / Math.abs(speed);
//						console.log(`speed is ${speed}px/1cycle(${intervalTime}ms)`)

						inertiaTimer = setInterval(() => {
//							console.log(`now speed is ${speed}px/1cycle(${intervalTime}ms)`)
							if (nowTop > maxTop) {
								clearInterval(inertiaTimer)
								// if (refresh) -> moveTo refreshTop else -> moveTo maxTop
								if (nowTop - maxTop > refreshTop && this.isRefresh) {
									inertiaTimer = this.moveTo(maxTop + refreshTop)
								} else if (nowTop - maxTop > refreshTop && !this.isRefresh) {
									this.refresh();
//									console.log('fresh true')
								} else {
									inertiaTimer = this.moveTo(maxTop)
								}
							} else if (nowTop < minTop) {
								clearInterval(inertiaTimer)
								inertiaTimer = this.moveTo(minTop)
							} else if (Math.round(speed) === 0) {
								clearInterval(inertiaTimer)
							} else {
								nowTop += speed;
								speed += direction;
								this.setProElementTop(nowTop, minTop, maxTop)
							}

						}, intervalTime)

						document.removeEventListener('touchmove', touchMove)
						document.removeEventListener('touchend', touchEnd)
					}
					document.addEventListener('touchend', touchEnd, {passive: true})
				}, {passive: true})
			}

		}

	}
</script>

<style lang="stylus">
    @import "../../styles/common.styl"
    .activeCancel
        display inline !important

    ::-moz-placeholder
        color: #fff
    ::-webkit-input-placeholder
        color: #fff
    input[type="search"]::-webkit-search-cancel-button
        display none
    input[type="search"]
        -webkit-appearance none
    header
        display flex
        position fixed
        z-index 999
        top 0
        background $mainColor
        padding .3rem 0
        width 100%
        .search-input
            width 12rem
            margin-left 1rem
            border-bottom 1px solid $assistantColor
            background $mainColor
            overflow hidden
            input
                padding .2rem
                border none
                font-size .65rem
                outline none
                color $assistantColor
                width 10rem
                line-height 1.05rem
                background $mainColor
                &:focus
                    color $assistantColor
            .search-icon
                display block
                float left
                z-index 1000
                color $assistantColor
                margin: .3rem .2rem 0 0
                font-size .9rem
            .cancel
                borderRadius(50%)
                color $mainColor
                background $assistantColor
                font-size .5rem
                padding .1rem
                position absolute
                right 3rem
                margin-top .3rem
                display none
    main
        position absolute
        top 2.07rem
        bottom 2rem
        width 100%
        overflow hidden
        background $lowerGrayColor
        box-sizing border-box
        .products
            width 100%
            position absolute
            .refresh
                top -40px
                horizontalMiddle()
                color $mainColor
                border-radius 50%
                height 30px
                width: 30px
                box-shadow 0 0 2px 2px $grayColor
                text-align center
                line-height 30px
                font-size 15px
                background: $assistantColor
                .icon
                    display block
                    width 15px
                    height 15px
                    margin 7px auto 7px auto
            section
                width 100%
                color $blackColor
                height 6rem
                margin-bottom .4rem
                background $assistantColor
                padding-top .5rem
                padding-bottom .5rem
                a
                    box-sizing border-box
                    display block
                    height 100%
                    text-decoration none
                    color $blackColor
                    font-size .85rem
                    position relative
                    padding 0 .5rem
                    img
                        height 2rem
                        width 2rem
                        float left
                    .title
                        font-weight bold
                        font-size .8rem
                        color #4c4c4c
                    .address
                        font-size .5rem
                        margin .4rem 0
                    .attributes
                        display flex
                        margin-bottom .7rem
                        .attribute
                            border-radius .1rem
                            color $grayColor
                            background $lowerGrayColor
                            padding .2rem
                            min-width 1.5rem
                            font-size .4rem
                            text-align center
                            margin-right .2rem
                    .right
                        position relative
                        float left
                        margin-left .2rem
                        height 2rem
                        .owner
                            font-size .8rem
                            color #000
                        .contact
                            font-size .6rem
                            position absolute
                            bottom 0
                    .topRight
                        position absolute
                        right .5rem
                        text-align right
                        .price
                            font-size .7rem
                            color $mainColor
                        .time
                            font-size .6rem
                            line-height 1.5rem
                    .bottom
                        height 1.2rem
                        .time
                            font-size .5rem
                            float left
                        .detail
                            display block
                            float right
                            background $mainColor
                            font-size .6rem
                            padding .25rem
                            border-radius .2rem
                            margin-top .1rem
                &:nth-last-child(2)
                    margin-bottom 0

            .loading
                height 1rem
                line-height 1rem
                font-size .6rem
                text-align center
                color $grayColor
</style>
